package com.ihunanren.common.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.ihunanren.common.io.excel.Excel;
import com.ihunanren.common.io.excel.ExcelCell;
import com.ihunanren.common.io.excel.ExcelRow;

public class ExcelReader {

	private final String excelFilePath;

	public ExcelReader(String excelFilePath) {
		if (Strings.isNullOrEmpty(excelFilePath))
			throw new IllegalArgumentException("excelFilePath is required!");
		this.excelFilePath = excelFilePath;
	}

	@SuppressWarnings("deprecation")
	public Excel getExcel() throws FileNotFoundException, IOException {
		// 将被表示成1.3922433397E10的手机号转化为13922433397,不一定是最好的转换方法
		DecimalFormat df = new DecimalFormat("#");
		// 创建对Excel工作簿文件的引用
		
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelFilePath));
		List<ExcelRow> excelRows = Lists.newArrayList();
		for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
			if (null != workbook.getSheetAt(numSheets)) {
				HSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet
				for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) {
					if (null != aSheet.getRow(rowNumOfSheet)) {
						HSSFRow aRow = aSheet.getRow(rowNumOfSheet);
						int cellCount = aRow.getLastCellNum();
						List<ExcelCell> cells = Lists.newArrayList();
						for (short cellNumOfRow = 0; cellNumOfRow <= cellCount; cellNumOfRow++) {
							ExcelCell cell =  null;
							if (null != aRow.getCell(cellNumOfRow)) {
								HSSFCell aCell = aRow.getCell(cellNumOfRow);
								int cellType = aCell.getCellType();
								switch (cellType) {
								case 0:// Numeric
									String strCell = df.format(aCell
											.getNumericCellValue());
									cell = new ExcelCell(strCell);
									break;
								case 1:// String
									cell = new ExcelCell(aCell.getStringCellValue());
									break;
								default:
									// System.out.println("格式不对不读");//其它格式的数据
								}
							}
							if(cell != null){
								cells.add(cell);
							}
						}
						excelRows.add(new ExcelRow(cellCount, cells));
					}
				}
			}
		}
		return new Excel(excelRows);
	}
	
	public static void main(String[] args) {
		try {
			Excel excel = new ExcelReader("d:/x.xls").getExcel();
			System.out.println(excel.getARow(0).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
